package com.example.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    // 环绕通知，计算方法执行耗时
    @Around("execution(* com.example.service.UserService.*(..))")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 执行目标方法
        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        logger.info("执行方法: " + joinPoint.getSignature() + "，耗时: " + duration + " 毫秒");

        return result;
    }

    // 异常通知，处理方法抛出的异常
    @AfterThrowing(pointcut = "execution(* com.example.service.UserService.*(..))", throwing = "ex")
    public void logException(Exception ex) {
        logger.error("发生异常: " + ex.getMessage());
    }
}
